package main

import (
	"MASSTEST/poc"
	massdb_v1 "MASSTEST/poc/engine/massdb/massdb.v1"
	"MASSTEST/poc/pocutil"
	"MASSTEST/pocec"
	"encoding/hex"
	"path/filepath"
	"strconv"
	"strings"
)

func getProof(mdb *massdb_v1.MassDBV1, challenge pocutil.Hash, pkHash pocutil.Hash) (proof *poc.Proof, err error) {

	cShort := pocutil.CutHash(challenge, mdb.BitLength())
	proof = &poc.Proof{BitLength: mdb.BitLength()}
	proof.X, proof.XPrime, err = mdb.HashMapB.Get(cShort)
	if err != nil {
		return
	}
	if err = poc.VerifyProof(proof, pkHash, challenge); err != nil {
		return nil, err
	}
	return proof, nil
}

func getPath(rootPath string, ordinal int64, pubKey *pocec.PublicKey, bitLength int) (path string) {
	pubKeyString := hex.EncodeToString(pubKey.SerializeCompressed())
	absPath := strings.Join([]string{strconv.Itoa(int(ordinal)), pubKeyString, strconv.Itoa(bitLength)}, "_")
	return filepath.Join(rootPath, absPath)
}

func pubKeyFromString(sPk string) (*pocec.PublicKey, error) {
	bPk, err := hex.DecodeString(sPk)
	if err != nil {
		return nil, err
	}
	pk, err := pocec.ParsePubKey(bPk, pocec.S256())
	if err != nil {
		return nil, err
	}
	return pk, nil
}

func privateKeyFromString(sSk string) (*pocec.PrivateKey, *pocec.PublicKey, error) {
	bSk, err := hex.DecodeString(sSk)
	if err != nil {
		return nil, nil, err
	}
	sk, pk := pocec.PrivKeyFromBytes(pocec.S256(), bSk)
	return sk, pk, nil
}

func signatureFromString(sSig string) (*pocec.Signature, error) {
	bSig, err := hex.DecodeString(sSig)
	if err != nil {
		return nil, err
	}
	sig, err := pocec.ParseSignature(bSig, pocec.S256())
	if err != nil {
		return nil, err
	}
	return sig, nil
}
